package com.sapient.mompoc.service.impl;

import com.sapient.mompoc.dao.OrderDAO;
import com.sapient.mompoc.dao.ProductDAO;
import com.sapient.mompoc.dao.impl.OrderDAOImpl;
import com.sapient.mompoc.dao.impl.ProductDAOImpl;
import com.sapient.mompoc.exception.OrderNotFoundException;
import com.sapient.mompoc.exception.OrderValidationException;
import com.sapient.mompoc.model.LineItem;
import com.sapient.mompoc.model.Order;
import com.sapient.mompoc.model.Product;
import com.sapient.mompoc.service.OrderService;

/**
 * Default Implementation of Order Service. This is a mock implementation.
 * 
 * @author asudar
 */
public class OrderServiceImpl implements OrderService {
	/**
	 * Order DAO ref
	 */

	private ProductDAO productDAO = new ProductDAOImpl();
	private OrderDAO orderDAO = new OrderDAOImpl();
	private static OrderServiceImpl orderServiceImpl = new OrderServiceImpl();

	private OrderServiceImpl() {
	}

	public Product getProduct(Long id) {
		return productDAO.getProduct(id);
	}

	private void populateProduct(Order order) {
		for (LineItem lineItem : order.getLineItems()) {
			// Doing this as the product in line item might be a complete
			// product
			// object. This is for demo only not to be taken as any pattern :-)
			lineItem.setProduct(getProduct(lineItem.getProduct().getId()));
		}
	}

	public void persist(Order order) throws OrderValidationException {
		if (order.getLineItems().size() == 0) {
			OrderValidationException ove = new OrderValidationException(
					"Invalid Order");

			throw ove;
		}

		populateProduct(order);
		System.out.println("Populated Order:" + order);
		orderDAO.persist(order);
	}

	/**
	 * Gets an Order provided the <code>orderId</code>
	 * 
	 * @param orderId
	 *            Order Id
	 * @return The Order
	 * @throws OrderNotFoundException
	 */
	public Order getOrder(Long orderId) throws OrderNotFoundException {
		Order order = orderDAO.getOrder(orderId);

		return order;
	}

	/**
	 * @param orderId
	 *            Id of the order to delete.
	 */
	public void delete(Long orderId) {
		orderDAO.delete(orderId);
	}

	public void setOrderDao(OrderDAO orderDao) {
		this.orderDAO = orderDao;
	}

	public static OrderService getInstance() {
		return orderServiceImpl;
	}
}
